import { reactive } from 'vue';

export default function useHooks() {
  const hooks = reactive({
    // 存储所有 hooks
    hooks: {},
  });

  /**
   * Add listener to plugin hooks system.
   *
   * @param {string} hookName The hook name.
   * @param {Function} callback The listener function to add.
   */
  const addHook = (hookName, callback) => {
    // console.log(`addHook hookName👉`, hookName)
    if (!hooks.hooks[hookName]) {
      hooks.hooks[hookName] = [];
    }

    const existingHooks = hooks.hooks[hookName];

    // exclude repeat hook
    if (existingHooks.includes(callback)) {
      console.warn(`Repeat hook name: ${hookName}`);
    } else {
      existingHooks.push(callback);
    }
  };

  /**
   * Trigger hook.
   *
   * @param {string} hookName The hook name.
   * @param {...any} args Arguments to pass to the hook callbacks.
   */
  const triggerHook = (hookName, ...args) => {
    // console.log(`triggerHook hookName👉`, hookName)
    const existingHooks = hooks.hooks[hookName];
    // console.log(`existingHooks 👉`,existingHooks)
    if (existingHooks) {
      existingHooks.forEach((hook) => {
        // console.log(`hookName 👉`, hookName)
        // console.log(`hook 👉`, hook)
        // console.log(`...args 👉`, ...args)
        hook(...args); // Call the hook with provided arguments
      });
    }
    // else {
    //   console.warn(`Can't find hook name: ${hookName}`);
    // }
  };

  return { addHook, triggerHook };
}
